package com.qyhl.webtv.commonlib.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.RemoteException;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.RequiresPermission;

import com.qyhl.webtv.commonlib.utils.cache.SpfManager;

import java.util.Objects;
import java.util.UUID;

public class DeviceUtils {
    private static final String KEY_UDID = "KEY_UDID";
    private volatile static String udid;


    /**
     * Return the unique device id.
     * <pre>{1}{UUID(macAddress)}</pre>
     * <pre>{2}{UUID(androidId )}</pre>
     * <pre>{9}{UUID(random    )}</pre>
     *
     * @return the unique device id
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getUniqueDeviceId(Context context) {
        return getUniqueDeviceId("", true, context);
    }

    /**
     * Return the unique device id.
     * <pre>android 10 deprecated {prefix}{1}{UUID(macAddress)}</pre>
     * <pre>{prefix}{2}{UUID(androidId )}</pre>
     * <pre>{prefix}{9}{UUID(random    )}</pre>
     *
     * @param prefix The prefix of the unique device id.
     * @return the unique device id
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getUniqueDeviceId(String prefix, Context context) {
        return getUniqueDeviceId(prefix, true, context);
    }

    /**
     * Return the unique device id.
     * <pre>{1}{UUID(macAddress)}</pre>
     * <pre>{2}{UUID(androidId )}</pre>
     * <pre>{9}{UUID(random    )}</pre>
     *
     * @param useCache True to use cache, false otherwise.
     * @return the unique device id
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getUniqueDeviceId(boolean useCache, Context context) {
        return getUniqueDeviceId("", useCache, context);
    }

    /**
     * Return the unique device id.
     * <pre>android 10 deprecated {prefix}{1}{UUID(macAddress)}</pre>
     * <pre>{prefix}{2}{UUID(androidId )}</pre>
     * <pre>{prefix}{9}{UUID(random    )}</pre>
     *
     * @param prefix   The prefix of the unique device id.
     * @param useCache True to use cache, false otherwise.
     * @return the unique device id
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getUniqueDeviceId(String prefix, boolean useCache, Context context) {
        if (!useCache) {
            return getUniqueDeviceIdReal(prefix, context);
        }
        if (udid == null) {
            synchronized (DeviceUtils.class) {
                if (udid == null) {
                    final String id = SpfManager.getInstance(context).getString(KEY_UDID, null);
                    if (id != null) {
                        udid = id;
                        return udid;
                    }
                    return getUniqueDeviceIdReal(prefix, context);
                }
            }
        }
        return udid;
    }

    private static String getUniqueDeviceIdReal(String prefix, Context context) {
        try {
            final String androidId = getAndroidID(context);
            if (!TextUtils.isEmpty(androidId)) {
                return saveUdid(prefix + 2, androidId, context);
            }

        } catch (Exception ignore) {/**/}
        return saveUdid(prefix + 9, "", context);
    }

    private static String saveUdid(String prefix, String id, Context context) {
        udid = getUdid(prefix, id);
        SpfManager.getInstance(context).put(KEY_UDID, udid);
        return udid;
    }

    /**
     * Return the android id of device.
     *
     * @return the android id of device
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidID(Context context) {
        String id = Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.ANDROID_ID
        );
        if ("9774d56d682e549c".equals(id)) return "";
        return id == null ? "" : id;
    }

    private static String getUdid(String prefix, String id) {
        if (id.equals("")) {
            return prefix + UUID.randomUUID().toString().replace("-", "");
        }
        return prefix + UUID.nameUUIDFromBytes(id.getBytes()).toString().replace("-", "");
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getDeviceId(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return Objects.requireNonNull(telephonyManager).getDeviceId().toString();
        } catch (Exception e) {
            return "";
        }
    }

}
